package com.llc.spring.cloud.eureka.client.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * time 2018/7/31 10:34
 *
 * @author xiaojie.zhu <br>
 */
@Component
public class ErrorHandler implements HandlerExceptionResolver {
    public final static Logger LOG = LoggerFactory.getLogger(ErrorHandler.class);

    @Override
    public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse response, Object o, Exception e) {
        LOG.error(e.getMessage(),e);
        //500
        try {
            response.setCharacterEncoding("UTF-8");
            response.setContentType("text/html;charset=utf-8");
            response.setStatus(500);
            PrintWriter writer = response.getWriter();
            writer.write(e.getClass().getName() + " : " + e.getMessage());
            writer.close();
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        return null;
    }
}
